﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using System.Threading;

namespace MangaReader
{
    public partial class VnSharingForm : Form
    {
        MangaInfo manga = new MangaInfo();
        string pathSaveTo = "";
        public VnSharingForm()
        {
            InitializeComponent();
        }

        private string siteList = "http://truyen.vnsharing.net/DanhSach?page=";
        List<MangaInfo> mangaList = new List<MangaInfo>();
        int totalPages = 1;

        private void btnGetMangaDetail_Click(object sender, EventArgs e)
        {
            if (txtLink.Text != "")
            {
                MangaInfo currentManga = DownloadMangaDetail(txtLink.Text);
                if (currentManga != null)
                    ShowMangaDetail(currentManga);
            }
            else
            {
                MessageBox.Show("You should choose one manga or type your link you want to show");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="link"></param>
        /// <returns>True: downloaded manga detail, false: can't load</returns>
        private MangaInfo DownloadMangaDetail(string link)
        {
            try
            {
                DownloadHelper dlHelper = new DownloadHelper();

                string content = dlHelper.GetHtmlFromUrl(link);
                if (content == "")
                {
                    MessageBox.Show("Can't load data from server. Please try again.");
                    return null;
                }
                content = HttpUtility.HtmlDecode(content);


                VnSharing vnSharing = new VnSharing();
                MangaInfo manga = vnSharing.GetMangaInfo(content);
                manga.LinkManga = link;

                return manga;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        private void ShowMangaDetail(MangaInfo manga)
        {
            this.txtTitle.Text = manga.Tilte;

            if (manga.Genres != null)
            {
                this.txtGenres.Text = "";
                for (int index = 0; index < manga.Genres.Count(); index++)
                {
                    if (index == manga.Genres.Count() - 1)
                        this.txtGenres.Text += manga.Genres[index];
                    else
                        this.txtGenres.Text += manga.Genres[index] + ", ";
                }
            }

            if (manga.Authors != null)
            {
                this.lblAuthors.Text = "";
                for (int index = 0; index < manga.Authors.Count(); index++)
                {
                    if (index == manga.Authors.Count() - 1)
                        this.lblAuthors.Text += manga.Authors[index];
                    else
                        this.lblAuthors.Text += manga.Authors[index] + ", ";
                }
            }

            this.lblTranslatorGroup.Text = manga.TranslatorGroup;

            this.lblStatus.Text = manga.Status;

            this.lblViews.Text = manga.Views.ToString();
            this.txtSummary.Text = manga.Summary;

            this.imgMangaPicture.ImageLocation = manga.ImageLink;

            this.txtLink.Text = manga.LinkManga;
            dgvChapterList.Rows.Clear();
            if (manga.Chapters.Count > 0)
            {
                for (int index = 0; index < manga.Chapters.Count; index++)
                {
                    dgvChapterList.Rows.Add(manga.Chapters[index].Title,manga.Chapters[index].Link, "Download" ,GetFolderFromLink(manga.Chapters[index].Link));
                }
            }
        }

        private string GetFolderFromLink(string link)
        {
            return link.Substring(link.LastIndexOf("/") + 1);
        }

        private void dgvChapterList_CellContentClick(object sender, DataGridViewCellEventArgs args)
        {
            switch (args.ColumnIndex)
            {
                case 0: // Title LinkLabel
                    {
                        // View Online
                        DialogResult dlgResult = MessageBox.Show("Do you want to view this chapter on browser?", "Confirm", MessageBoxButtons.OKCancel);
                        if (dlgResult == DialogResult.OK)
                        {
                            string link = dgvChapterList.Rows[args.RowIndex].Cells[1].Value.ToString();
                            ShowChapterOnBrowser(link);
                        }
                        break;
                    }
                case 2: // Button Download
                    {
                        try
                        {
                            // Download
                            DialogResult dlgResult = MessageBox.Show("Do you want to download this chapter?", "Confirm", MessageBoxButtons.OKCancel);
                            if (dlgResult == DialogResult.OK)
                            {
                                ChapterInfo viewChap = new ChapterInfo();
                                VnSharing vnSharing = new VnSharing();
                                viewChap.Link = dgvChapterList.Rows[args.RowIndex].Cells[1].Value.ToString();

                                DownloadHelper dlHelper = new DownloadHelper();

                                string downloadedContent = dlHelper.GetHtmlFromUrl(viewChap.Link);
                                viewChap.ImageLinks = vnSharing.GetImageLinksOfChapter(downloadedContent);

                                string chapterFolder = GetFolderFromLink(dgvChapterList.Rows[args.RowIndex].Cells[1].Value.ToString());
                                ChapterDownload chapterDownload = new ChapterDownload(viewChap.ImageLinks, manga, chapterFolder);
                                Thread download = new Thread(chapterDownload.Start);
                                download.Start();
                                //chapterDownload.Start();
                            }
                            break;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            break;
                        }
                    }
            }

           
        }

        private void ShowChapterOnBrowser(string link)
        {
            #region "CODE FOR OPEN BROWSER"
            //string strUrl = (string)this.dgvMangaList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            try
            {
                System.Diagnostics.Process.Start(link);
            }

            catch (Exception exc1)
            {
                // System.ComponentModel.Win32Exception is a known exception that occurs when Firefox is default browser. 
                // It actually opens the browser but STILL throws this exception so we can just ignore it.  If not this exception,
                // then attempt to open the URL in IE instead.
                if (exc1.GetType().ToString() != "System.ComponentModel.Win32Exception")
                {
                    // sometimes throws exception so we have to just ignore
                    // this is a common .NET bug that no one online really has a great reason for so now we just need to try to open
                    // the URL using IE if we can.
                    try
                    {
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("IExplore.exe", link);
                        System.Diagnostics.Process.Start(startInfo);
                        startInfo = null;
                    }
                    catch (Exception exc2)
                    {
                        // still nothing we can do so just show the error to the user here.
                        MessageBox.Show("Can't show your chapter on browser. Error: " + exc2.Message);
                    }
                }
            }
            #endregion
        }

        private void btnDownloadAll_Click(object sender, EventArgs e)
        {
            DialogResult dlgResult = MessageBox.Show("Do you want to download this chapter?", "Confirm", MessageBoxButtons.OKCancel);
            if (dlgResult == DialogResult.OK)
            {
                ChapterInfo viewChap = new ChapterInfo();
                VnSharing vnSharing = new VnSharing();
                for (int index = 0; index < dgvChapterList.Rows.Count; index++)
                {
                    viewChap.Link = dgvChapterList.Rows[index].Cells[1].Value.ToString();
                    DownloadHelper dlHelper = new DownloadHelper();

                    string downloadedContent = dlHelper.GetHtmlFromUrl(viewChap.Link);
                    viewChap.ImageLinks = vnSharing.GetImageLinksOfChapter(downloadedContent);

                    string chapterTitle = dgvChapterList.Rows[index].Cells[1].Value.ToString();
                    ChapterDownload chapterDownload = new ChapterDownload(viewChap.ImageLinks, manga, GetFolderFromLink(chapterTitle));
                    chapterDownload.Start();
                }
            }
        }

        private void btnGetListFromPage_Click(object sender, EventArgs e)
        {
            try
            {
                int page = int.Parse(this.nudPager.Value.ToString());

                mangaList = GetMangaList(page, ref totalPages);
                ShowMangaList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void VnSharingForm_Load(object sender, EventArgs e)
        {
            mangaList = GetMangaList(1, ref totalPages);
            this.nudPager.Maximum = totalPages;
            ShowMangaList();
            //this.Width = 580;

            this.txtSaveTo.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            // Set the help text description for the FolderBrowserDialog.
            this.folderBrowserDialog1.Description =
                "Select the directory that you want to use as the default.";

            // Do not allow the user to create new files via the FolderBrowserDialog.
            this.folderBrowserDialog1.ShowNewFolderButton = true;

            // Default to the My Documents folder.
            this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;
        }

        private void ShowMangaList()
        {
            this.dgvMangaList.Rows.Clear();

            foreach (MangaInfo manga in mangaList)
            {
                this.dgvMangaList.Rows.Add(manga.Tilte, manga.LinkManga, "View Detail");
            }
        }

        private List<MangaInfo> GetMangaList(int page, ref int totalPages)
        {
            List<MangaInfo> tmpList = new List<MangaInfo>();

            DownloadHelper dlHelper = new DownloadHelper();

            string downloadedContent = dlHelper.GetHtmlFromUrl(siteList + page.ToString());


            VnSharing vnSharing = new VnSharing();
            tmpList = vnSharing.GetMangaList(downloadedContent, ref totalPages);

            this.nudPager.Maximum = totalPages;

            return tmpList;
        }

        private void dgvMangaList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvChapterList.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            if (e.ColumnIndex == 2)
            {
                try
                {
                    string link = this.dgvMangaList.Rows[e.RowIndex].Cells[1].Value.ToString();
                    MangaInfo currentManga = DownloadMangaDetail(link);
                    manga = currentManga;
                    manga.MangaFolder = GetFolderFromLink(manga.LinkManga);

                    if (currentManga != null)
                        ShowMangaDetail(currentManga);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btnSaveTo_Click(object sender, EventArgs e)
        {
            // MessageBox.Show(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.txtSaveTo.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void txtSaveTo_TextChanged(object sender, EventArgs e)
        {
            pathSaveTo = this.txtSaveTo.Text;
        }
    }
}
